Skip to content

prevent infinite recursion when validating schemas #394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from

Conversation

cody-greene
Copy link

@cody-greene cody-greene commented May 16, 2021

The Problem:
Summary:
Infinite recursion is possible in src/utils.ts:mapDeep()
This will fix a few cases of "Uncaught RangeError: Maximum call stack size exceeded"

Detail:
Let's say I define a schema like this:

const ListNode = {
  type: 'object',
  properties: {
    value: {type: 'string'},
    next: {$ref: '#'} // Circular reference
  }
}

// If I call compile() twice on the same schema object (with different options, for example)
import {compile} from 'json-schema-to-typescript'
const prettyContent = await compile(ListNode)
// The first call is fine

// But notice the ListNode object was modified (see $RefParser.dereference)
console.log(ListNode)
//{
//  type: 'object',
//  properties: { value: {type: 'string'}, next: [Circular *1] }
//}

const uglyContent = await compile(ListNode, {format: false})
// Uncaught RangeError: Maximum call stack size exceeded
// Uh-oh! There's infinite recursion happening.

// And of course I don't actually have to call compile() twice.
// I could just as well define my schema like this in the first place:
ListNode.properties.next = ListNode

The Solution:
Summary:
To fix this we can modify the recursive function in question to track seen objects and return early if one is seen second time (or more).

Detail:
replace src/utils.ts:mapDeep() with crawl()

  • considering where mapDeep() is used, mutation is not necessary so we can remove the use of lodash's mapValues() and just iterate over Object.keys(obj)

use a Set to detect reference cycles

  • it's fast and has broad browser support which includes IE11

Final note: Unfortunately json-schema-ref-parser has the exact same problem so we'll need to wait for APIDevTools/json-schema-ref-parser#231 to merge before this is really solved.

@bcherny
Copy link
Owner

bcherny commented May 16, 2022

Thanks for the contribution, and sorry for the delay in merging this in. Closing since 4837ef2 is now merged.

@bcherny bcherny closed this May 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants